package com.liveinstars.im.endpoint;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.liveinstars.im.common.enums.IMExceptionEnum;
import com.liveinstars.im.core.service.FansService;
import com.liveinstars.api.im.FansApiService;
import com.liveinstars.api.im.vo.FansVO;
import com.liveinstars.api.im.vo.UserFansInfoVO;
import com.onepiece.shipelves.common.Result;
import com.onepiece.shipelves.common.enums.SystemExceptionEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RestController
public class FansApiEndPoint implements FansApiService {

    @Autowired
    FansService fansService;


    @Override
    public String getFansList(@RequestParam(value = "userId", defaultValue = "") Long userId, @RequestParam(value = "fansId", defaultValue = "") Long fansId) {
        Result<List<FansVO>> result = new Result<>();
        try {
            List<FansVO> list = Lists.newArrayList();
            if (userId != null && userId != 0) {
                list = fansService.listFansByUserId(userId);
                result.setData(list);
            } else if(fansId != null && fansId != 0) {
                list = fansService.listFollowByUserId(fansId);
                result.setData(list);
            } else {
                result = SystemExceptionEnum.MISSING_REQUEST_PARAM.createResult();
            }
            return JSON.toJSONString(result);
        } catch (Exception e) {
            result = SystemExceptionEnum.UN_KNOW_ERROR.createResult();
            return JSON.toJSONString(result);
        }
    }

    @Override
    public Result<FansVO> getFansByUserIdAndFansId(@RequestParam(value = "userId", defaultValue = "") Long userId, @RequestParam(value = "fansId", defaultValue = "") Long fansId) {
        Result<FansVO> result = new Result<>();
        FansVO fansVO = fansService.getFansByUserIdAndFansId(userId, fansId);
        if (fansVO != null) {
            result.setData(fansVO);
        } else {
            result = IMExceptionEnum.USER_IS_NOT_EXIST.createResult();
        }
        return result;
    }

    @Override
    public Result<FansVO> addFans(@RequestBody FansVO fansVO) {
        Result<FansVO> result = new Result<FansVO>();
        try {
            fansService.addFans(fansVO);
            result.setData(fansVO);
        } catch (Exception e) {
            result = IMExceptionEnum.USER_IS_NOT_EXIST.createResult();
        }
        return result;
    }

    @Override
    public Result<UserFansInfoVO> getFansCount(@RequestParam(value = "userId", defaultValue = "") Long userId) {
        UserFansInfoVO userFansInfo = fansService.getUserFansInfo(userId);
        Result<UserFansInfoVO> result = new Result<>();
        result.setData(userFansInfo);
        return result;
    }
}
